const Router = require('koa-router');
let router = new Router();
const mongoose = require('mongoose');

//发送token,解密token
const jwt = require('jsonwebtoken');
const jwtKoa = require('koa-jwt');
const util = require('util');
const verify = util.promisify(jwt.verify) // 解密
const secret = 'jwt demo';

router.get('/', async (ctx) => {
    ctx.body = '这是用户操作页面';
});
router.get('/allUsers',async (ctx)=>{
    let content = mongoose.model('User');
    await content.find({}).exec().then((resl)=>{
        ctx.body = {
            code:200,
            data:resl
        }
    }).catch((error)=>{
        ctx.body = {
            code:500,
            data:[]
        }
    });
});
router.post('/delUser', async (ctx) => {
    let userData= ctx.request.body;
    let user = mongoose.model('User');
    let userId= userData._id;
    await user.remove({_id:userId}).then(() => {
        ctx.body = {
            code: 200,
            msg: '删除成功!'
        }
    }).catch((error) => {
        ctx.body = {
            code: 500,
            msg: '删除失败!'
        }
    });
});
// 注册 
router.post('/register', async (ctx) => {

    let userName = mongoose.model('User');
    let newUser = new userName(ctx.request.body);
    await newUser.save().then(() => {
        ctx.body = {
            code: 200,
            msg: '注册成功!'
        }
    }).catch((error) => {
        ctx.body = {
            code: 500,
            msg: '注册失败!'
        }
    });
});
//登录
router.post('/loging', async (ctx) => {
    let userData= ctx.request.body;
    let userName = userData.userNames;
    let password = userData.password;
    const User = mongoose.model('User');
    
    let userToken = {
        name: userName
    }
    const token = jwt.sign(userToken, secret, {expiresIn: '1h'})  //token签名 有效期为1小时


    await User.findOne({
        userName: userName
    }).exec().then(async (reslt) => {
        console.log(reslt)
        if (reslt) {
            let newUser = new User();
            await newUser.comparePassword(password, reslt.password).then((isMatch) => {
                if(isMatch){
                    ctx.body = {
                        code: 200,
                        message: '成功',
                        token
                    };
                }
            }).catch((error)=>{
                ctx.body = {
                    code: 500,
                    message: error
                };
            })
        }
    })
})

module.exports = router;